package com.wrox.earthquake;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListFragment;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;

public class EarthquakeListFragment extends ListFragment {
	private static final String TAG = "EARTHQUAKE";
	private Handler handler = new Handler();
	private ArrayAdapter<Quake> aa;
	private ArrayList<Quake> quakes;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		quakes = new ArrayList<Quake>();
		aa = new ArrayAdapter<Quake>(getActivity(), android.R.layout.simple_list_item_1, quakes);
		this.setListAdapter(aa);
		
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				refreshEarthquakes();				
			}			
		});
		t.start();
	}

	protected void refreshEarthquakes() {
		URL url;
		try {
			String quakeFeed = this.getString(R.string.quake_feed);
			url = new URL(quakeFeed);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			int responseCode = conn.getResponseCode();
			
			if (responseCode != HttpURLConnection.HTTP_OK) {
				Log.d(TAG, "response code is not HTTP_OK");
				return;
			}
			
			InputStream in = conn.getInputStream();
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document dom = db.parse(in);
			Element docEle = dom.getDocumentElement();
			
			quakes.clear();
			NodeList nl = docEle.getElementsByTagName("entry");
			if (nl == null || nl.getLength() == 0) {
				Log.d(TAG, "empty <entry> list");
				return;
			}
			
			Log.v(TAG, "# of entries = " + nl.getLength());
			
			for (int i = 0; i < nl.getLength(); i++) {
				Element entry = (Element) nl.item(i);
				Element title = (Element) entry.getElementsByTagName("title").item(0);
				Element g = (Element) entry.getElementsByTagName("georss:point").item(0);
				Element when = (Element) entry.getElementsByTagName("updated").item(0);
				Element link = (Element) entry.getElementsByTagName("link").item(0);
				
				String details = title.getFirstChild().getNodeValue();
				//String hostname = "http://earthquake.usgs.gov";
				String linkString = link.getAttribute("href");
				
				String point = g.getFirstChild().getNodeValue();
				String dt = when.getFirstChild().getNodeValue();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
				Date qDate = new GregorianCalendar(0,0,0).getTime();
				try {
					qDate = sdf.parse(dt);
				} catch (Exception e) {
					Log.d(TAG, "error parsing date = " + dt);
				}
				
				String []location = point.split(" ");
				Location l = new Location("dummyGPS");
				l.setLatitude(Double.parseDouble(location[0]));
				l.setLongitude(Double.parseDouble(location[1]));
				
				String magnitudeString = details.split(" ")[1];
				double magnitude = Double.parseDouble(magnitudeString.substring(0, magnitudeString.length()-1));
				
				details = details.split(",")[1].trim();
				
				final Quake quake = new Quake(qDate, details, l, magnitude, linkString);
				
				handler.post(new Runnable() {
					@Override
					public void run() {
						addNewQuake(quake);						
					}					
				});
			}
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		}
	}

	protected void addNewQuake(Quake quake) {
		if (quake.getMagnitude() >= ((EarthquakeActivity)getActivity()).getMinimumMagnitude()) {
			quakes.add(quake);
			aa.notifyDataSetChanged();
		}
	}
		
}
